/*-----------------------------------------------------------------------------

 Copyright 2017 Hopsan Group

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


 The full license is available in the file LICENSE.
 For details about the 'Hopsan Group' or information about Authors and
 Contributors see the HOPSANGROUP and AUTHORS files that are located in
 the Hopsan source code root directory.

-----------------------------------------------------------------------------*/

#ifndef SIGNALPID_HPP_INCLUDED
#define SIGNALPID_HPP_INCLUDED

#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include "math.h"

//!
//! @file C:\HopsanTrunk\HOPSAN++\componentLibraries\defaultLibrary\Signal\Control\SignalPID.hpp
//! @author Petter Krus <petter.krus@liu.se>
//! @date Wed 23 Oct 2013 11:03:10
//! @brief PID controller
//! @ingroup SignalComponents
//!
//==This code has been autogenerated using Compgen==
//from 
/*{, C:, HopsanTrunk, HOPSAN++, CompgenModels}/SignalControlComponents.nb*/

using namespace hopsan;

class SignalPID : public ComponentSignal
{
private:
     double delayParts1[9];
     double delayParts2[9];
     double delayParts3[9];
     double delayParts4[9];
     Matrix jacobianMatrix;
     Vec systemEquations;
     Matrix delayedPart;
     int i;
     int iter;
     int mNoiter;
     double jsyseqnweight[4];
     int order[3];
     int mNstep;
//==This code has been autogenerated using Compgen==
     //inputVariables
     double yref;
     double y;
     double dy;
     double Kp;
     double KI;
     double Kd;
     double umin;
     double umax;
     //outputVariables
     double u;
     double Ierr;
     double uI;
     //Delay declarations
//==This code has been autogenerated using Compgen==
     //inputVariables pointers
     double *mpyref;
     double *mpy;
     double *mpdy;
     double *mpKp;
     double *mpKI;
     double *mpKd;
     double *mpumin;
     double *mpumax;
     //outputVariables pointers
     double *mpu;
     double *mpIerr;
     double *mpuI;
     Delay mDelayedPart10;
     Delay mDelayedPart20;
     Delay mDelayedPart30;
     Delay mDelayedPart31;
     EquationSystemSolver *mpSolver;

public:
     static Component *Creator()
     {
        return new SignalPID();
     }

     void configure()
     {
//==This code has been autogenerated using Compgen==

        mNstep=9;
        jacobianMatrix.create(3,3);
        systemEquations.create(3);
        delayedPart.create(4,6);
        mNoiter=2;
        jsyseqnweight[0]=1;
        jsyseqnweight[1]=0.67;
        jsyseqnweight[2]=0.5;
        jsyseqnweight[3]=0.5;


        //Add ports to the component
        //Add inputVariables to the component
            addInputVariable("yref","Reference value","",0.,&mpyref);
            addInputVariable("y","Actual value","",0.,&mpy);
            addInputVariable("dy","Differential of actual \
value","",0.,&mpdy);
            addInputVariable("Kp","Proportional gain","",1.,&mpKp);
            addInputVariable("KI","Integral gain","",1.,&mpKI);
            addInputVariable("Kd","Differential gain","",1.,&mpKd);
            addInputVariable("umin","Minium output signal","",-1.,&mpumin);
            addInputVariable("umax","Maximum output signal","",1.,&mpumax);

        //Add outputVariables to the component
            addOutputVariable("u","control signal","",0.,&mpu);
            addOutputVariable("Ierr","limited error","",0.,&mpIerr);
            addOutputVariable("uI","control signal from integral \
part","",0.,&mpuI);

//==This code has been autogenerated using Compgen==
        //Add constants/parameters
        mpSolver = new EquationSystemSolver(this,3);
     }

    void initialize()
     {
        //Read port variable pointers from nodes

        //Read variables from nodes

        //Read inputVariables from nodes
        yref = (*mpyref);
        y = (*mpy);
        dy = (*mpdy);
        Kp = (*mpKp);
        KI = (*mpKI);
        Kd = (*mpKd);
        umin = (*mpumin);
        umax = (*mpumax);

        //Read outputVariables from nodes
        u = (*mpu);
        Ierr = (*mpIerr);
        uI = (*mpuI);

//==This code has been autogenerated using Compgen==


        //Initialize delays
        delayParts3[1] = (-(Ierr*KI*mTimestep) - 2*uI)/2.;
        mDelayedPart31.initialize(mNstep,delayParts3[1]);

        delayedPart[1][1] = delayParts1[1];
        delayedPart[2][1] = delayParts2[1];
        delayedPart[3][1] = delayParts3[1];
     }
    void simulateOneTimestep()
     {
        Vec stateVar(3);
        Vec stateVark(3);
        Vec deltaStateVar(3);

        //Read variables from nodes

        //Read inputVariables from nodes
        yref = (*mpyref);
        y = (*mpy);
        dy = (*mpdy);
        Kp = (*mpKp);
        KI = (*mpKI);
        Kd = (*mpKd);
        umin = (*mpumin);
        umax = (*mpumax);

        //LocalExpressions

        //Initializing variable vector for Newton-Raphson
        stateVark[0] = u;
        stateVark[1] = Ierr;
        stateVark[2] = uI;

        //Iterative solution using Newton-Rapshson
        for(iter=1;iter<=mNoiter;iter++)
        {
         //PID
         //Differential-algebraic system of equation parts

          //Assemble differential-algebraic equations
          systemEquations[0] =u - limit(-(dy*Kd) + uI + Kp*(-y + \
yref),umin,umax);
          systemEquations[1] =Ierr - (-y + yref)*dxLimit(limit(-(dy*Kd) + uI \
+ Kp*(-y + yref),umin,umax),umin,umax);
          systemEquations[2] =-(Ierr*KI*mTimestep)/2. + uI + \
delayedPart[3][1];

          //Jacobian matrix
          jacobianMatrix[0][0] = 1;
          jacobianMatrix[0][1] = 0;
          jacobianMatrix[0][2] = -dxLimit(-(dy*Kd) + uI + Kp*(-y + \
yref),umin,umax);
          jacobianMatrix[1][0] = 0;
          jacobianMatrix[1][1] = 1;
          jacobianMatrix[1][2] = 0;
          jacobianMatrix[2][0] = 0;
          jacobianMatrix[2][1] = -(KI*mTimestep)/2.;
          jacobianMatrix[2][2] = 1;
//==This code has been autogenerated using Compgen==

          //Solving equation using LU-faktorisation
          mpSolver->solve(jacobianMatrix, systemEquations, stateVark, iter);
          u=stateVark[0];
          Ierr=stateVark[1];
          uI=stateVark[2];
        }

        //Calculate the delayed parts
        delayParts3[1] = (-(Ierr*KI*mTimestep) - 2*uI)/2.;

        delayedPart[1][1] = delayParts1[1];
        delayedPart[2][1] = delayParts2[1];
        delayedPart[3][1] = delayParts3[1];

        //Write new values to nodes
        //outputVariables
        (*mpu)=u;
        (*mpIerr)=Ierr;
        (*mpuI)=uI;

        //Update the delayed variabels
        mDelayedPart31.update(delayParts3[1]);

     }
    void deconfigure()
    {
        delete mpSolver;
    }
};
#endif // SIGNALPID_HPP_INCLUDED
